import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'state.dart';
import 'view.dart';
import 'package:yp/services/api.dart';

class HelpLogic extends GetxController {
  final HelpState state = HelpState();
  VoidCallback tabsChanged;
  @override
  void onInit() {
    super.onInit();
    queryHelpInfo('');
  }

  tabChanged(int index) {
    state.currentIndex = index;
    var contentList = state.contentInfo[state.currentIndex];
    if (contentList != null) {
      state.contentList = contentList;
    } else {
      queryHelpInfo(
          state.groupInfos[state.currentIndex]['group_num_id'].toString());
    }
  }

  queryHelpInfo(String groupId) {
    // 获取用户信息
    var params = {
      'group_num_id': groupId ?? '',
      'status_num_id': 2, //状态编号，1-待发布、2-已发布、3-已作废
      'group_query_sign': 1, //分组信息查询标识, 1：查询分组信息2：不查询
      'content_title': state.textCtrl.text ?? '',
      'page_num': state.pageIndex,
      'page_size': 10
    };
    Api.queryHelp(params).listen((event) {
      if (event['code'] == 0) {
        state.groupInfos = event['group_infos'];
        state.groupInfos.insert(0, {'group_name': '全部'});
        if (state.refreshCtrls == null) {
          state.refreshCtrls =
              state.groupInfos.map((_) => RefreshController()).toList();
        }
        List contentList = event['help_center_content_list'];
        // contentList = List.generate(
        //     20,
        //     (index) => {
        //           'content_title': '问题',
        //           'content_value':
        //               'https://t7.baidu.com/it/u=91673060,7145840&fm=193&f=GIF'
        //         });
        if (state.pageIndex == 1) {
          state.contentList = contentList;
        } else {
          state.contentList.addAll(contentList ?? []);
        }
        state.contentInfo[state.currentIndex] = state.contentList;
      }
      if (state.refreshCtrl.isRefresh) {
        state.refreshCtrl.refreshCompleted();
      }
      if (state.refreshCtrl.isLoading) {
        state.refreshCtrl.loadComplete();
      }
      tabsChanged();
      update();
    });
  }

  onRefresh() {
    state.pageIndex = 1;
    queryHelpInfo(state.groupInfos[state.currentIndex]['group_num_id']);
  }

  onLoadding() {
    state.pageIndex += 1;
    queryHelpInfo(state.groupInfos[state.currentIndex]['group_num_id']);
  }
}
